<template>
  <div>
    <the-navigation>
      <template #header-controls>
        <div class="control-panel">
          <el-button type="success" class="control-btn success" @click="startTimer">
            <el-icon><video-play /></el-icon>
            <span>开始</span>
          </el-button>
          <el-button type="danger" class="control-btn danger" @click="stopTimer">
            <el-icon><video-pause /></el-icon>
            <span>结束</span>
          </el-button>
          <el-button type="primary" class="control-btn primary" @click="resetSystem">
            <el-icon><refresh /></el-icon>
            <span>重置</span>
          </el-button>
        </div>
      </template>
    </the-navigation>
    
    <main class="main-content">
      <div class="data-cards">
        <div class="data-card time-card">
          <div class="card-icon">
            <el-icon><timer /></el-icon>
          </div>
          <div class="card-label">用时</div>
          <div class="card-value">
            {{ formatTime(currentTime) }}
            <span class="unit">秒</span>
          </div>
        </div>
        
        <div class="data-card pile-card">
          <div class="card-header">
            <div class="card-icon">
              <el-icon><warning /></el-icon>
            </div>
            <el-button class="edit-button" text @click="editPenalty">修改</el-button>
          </div>
          <div class="card-label">漏桩踢桩数量</div>
          <div class="card-value">
            {{ penaltyCount }}
            <span class="unit">个</span>
          </div>
        </div>
        
        <div class="data-card land-card">
          <div class="card-header">
            <div class="card-icon">
              <el-icon><position /></el-icon>
            </div>
            <el-button class="edit-button" text @click="toggleGroundTouch">修改</el-button>
          </div>
          <div class="card-label">浮脚落地</div>
          <div class="card-value">
            {{ groundTouch ? '是' : '否' }}
          </div>
        </div>
      </div>
      
      <!-- 桩桶可视化组件 -->
      <cone-visualizer ref="conesVisualizer" @status-change="handleConeStatusChange" />
      
      <!-- 最终成绩 -->
      <div class="final-result-text">
        <div class="result-section">
          <h3>最终成绩</h3>
          <div class="status-badge" :class="{ 'valid': isValidResult, 'invalid': !isValidResult }">
            {{ isValidResult ? '有效' : '无效' }}
          </div>
          <div class="final-score-value">{{ formatTime(finalScore) }}</div>
          <div class="score-note" v-if="penaltyCount > 0">
            包含 {{ penaltyCount }} 个漏桩踢桩惩罚时间
          </div>
        </div>
      </div>
      
      <!-- 成绩记录 -->
      <div class="records-section">
        <div class="records-title">成绩记录</div>
        <div class="records-actions">
          <el-button class="simple-button" @click="exportRecords">
            <el-icon><download /></el-icon>
            导出成绩记录
          </el-button>
          <el-button class="simple-button danger" :disabled="!selectedRecords.length" @click="batchDeleteRecords">
            <el-icon><delete /></el-icon>
            删除所选 ({{ selectedRecords.length }})
          </el-button>
        </div>
        
        <el-table 
          :data="records" 
          stripe 
          style="width: 100%" 
          class="records-table"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="timestamp" label="时间" min-width="160" />
          <el-table-column prop="time" label="原始用时" min-width="100">
            <template #default="scope">
              <span class="time-value">{{ formatTime(scope.row.time) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="penaltyCount" label="漏桩踢桩数" min-width="90" />
          <el-table-column prop="penaltyTime" label="罚时" min-width="90">
            <template #default="scope">
              <span class="penalty-value">+{{ scope.row.penaltyTime.toFixed(1) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="finalScore" label="最终成绩" min-width="110">
            <template #default="scope">
              <span class="final-score" :class="{'invalid': !scope.row.valid}">
                {{ scope.row.valid ? formatTime(scope.row.finalScore) : '无效' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="valid" label="状态" min-width="80">
            <template #default="scope">
              <span class="status" :class="{'invalid': !scope.row.valid}">
                {{ scope.row.valid ? '有效' : '无效' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="80">
            <template #default="scope">
              <el-button class="delete-btn" text type="danger" @click="deleteRecord(scope.$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </main>
    
    <!-- 漏桩踢桩修改对话框 -->
    <el-dialog
      v-model="penaltyDialogVisible"
      title="修改漏桩踢桩数量"
      width="300px"
    >
      <el-form>
        <el-form-item label="数量">
          <el-input-number v-model="editingPenaltyCount" :min="0" :max="20" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="penaltyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPenaltyEdit">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onBeforeUnmount, onMounted, watch, onActivated, onDeactivated } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import TheNavigation from '@/components/TheNavigation.vue'
import ConeVisualizer from '@/components/ConeVisualizer.vue'
import mqtt from 'mqtt'
import * as XLSX from 'xlsx'

// MQTT连接相关
const mqttStatus = ref('disconnected')
const mqttClient = ref(null)
const connectedDevices = ref(['DEVICE001']) // 默认设备
const activeDeviceId = ref('DEVICE001')

// 定时器引用
let timerInterval = null

// 比赛状态
const isTimerRunning = ref(false)
const currentTime = ref(0)
const startTime = ref(0)
const penaltyCount = ref(0) // 初始状态改为0
const groundTouch = ref(false)

// 修改对话框
const penaltyDialogVisible = ref(false)
const editingPenaltyCount = ref(0)

// 桩桶可视化组件引用
const conesVisualizer = ref(null)

// 成绩记录 - 改为空数组，从本地存储加载
const records = ref([])

// 添加一个标记变量，表示当前是否有一个进行中的比赛
const hasActiveRace = ref(false)

// 添加一个标记，表示当前是否是新比赛还是修改已有记录
const isNewRace = ref(true)

// 添加一个标记，表示当前记录是否已完成（收到结果消息）
const isRecordCompleted = ref(true)

// 当前活动记录的ID
const activeRecordId = ref(null)

// 选中的记录
const selectedRecords = ref([])

// 计算罚时
const penaltyTime = computed(() => {
  return penaltyCount.value * 0.2 // 每个漏桩或踢桩罚时0.2秒
})

// 计算最终成绩
const finalScore = computed(() => {
  return currentTime.value + penaltyTime.value
})

// 判断成绩是否有效
const isValidResult = computed(() => {
  // 如果浮脚落地或漏桩踢桩超过4个，则成绩无效
  return !groundTouch.value && penaltyCount.value <= 4
})

//连接MQTT服务器
function connectMqtt() {
  const options = {
    username: 'zxt',
    password: 'zyc123456',
    clean: true,
    connectTimeout: 4000,
    clientId: 'ipad_video_client_' + Math.random().toString(16).substring(2, 8)
  }

  console.log('🔄 正在连接MQTT服务器...')
  console.log(`连接信息: ws://192.168.31.245:8083/mqtt, 客户端ID: ${options.clientId}`)
  
  mqttClient.value = mqtt.connect('ws://192.168.31.245:8083/mqtt', options)

// function connectMqtt() {
//   const options = {
//     username: 'zxt',
//     password: '554908',
//     clean: true,
//     connectTimeout: 4000,
//     clientId: 'ipad_video_client_' + Math.random().toString(16).substring(2, 8)
//   }

//   console.log('🔄 正在连接MQTT服务器...')
//   console.log(`连接信息: ws://111.229.27.106:8083/mqtt, 客户端ID: ${options.clientId}`)
  
//   mqttClient.value = mqtt.connect('ws://111.229.27.106:8083/mqtt', options)

  mqttClient.value.on('connect', () => {
    console.log('🟢 MQTT服务器连接成功')
    mqttStatus.value = 'connected'
    
    // 订阅视频录制相关主题
    mqttClient.value.subscribe('roller/cam/MaixCAM/result', { qos: 1 }, (err) => {
      if (!err) {
        console.log('✅ 成功订阅录制结果主题')
      } else {
        console.error('❌ 订阅录制结果主题失败:', err)
      }
    })
    
    // 订阅与设备连接相关的主题
    console.log('订阅设备发现主题: roller/timer/start')
    mqttClient.value.subscribe('roller/timer/start', (err) => {
      if (!err) {
        console.log('✅ 成功订阅设备发现主题')
      } else {
        console.error('❌ 订阅设备发现主题失败:', err)
      }
    })
    
    // 确保至少有一个默认设备
    if (connectedDevices.value.length === 0) {
      console.log('添加默认设备DEVICE001到已连接设备列表')
      connectedDevices.value.push('DEVICE001')
    }
    
    // 延迟一点时间确保MQTT连接稳定后再订阅主题
    setTimeout(() => {
      subscribeToDeviceTopics()
      
      // 如果可视化组件已经就绪，则设置MQTT客户端
      if (conesVisualizer.value) {
        console.log('桩桶可视化组件已就绪，设置MQTT客户端')
        conesVisualizer.value.setMqttClient(mqttClient.value)
      } else {
        console.log('桩桶可视化组件尚未就绪，将通过watch监听器设置MQTT客户端')
      }
    }, 500)
  })

  mqttClient.value.on('message', (topic, message) => {
    try {
      console.log(`📩 收到MQTT消息: 主题=${topic}`)
      
      // 如果是视频系统的消息，交给视频播放器组件处理
      if (topic === 'roller/cam/MaixCAM/result') {
        // 这里不需要处理，VideoPlayback 组件会处理
        return
      }
      
      const data = JSON.parse(message.toString())
      console.log(`消息内容:`, data)
      
      if (topic === 'roller/timer/start') {
        console.log(`📣 处理设备连接消息: ${JSON.stringify(data)}`)
        handleDeviceConnection(data)
        return
      }
      
      // 处理特定设备的control主题
      if (topic.includes('/control')) {
        console.log(`🎮 处理控制命令: ${JSON.stringify(data)}`)
        handleTimerControl(data)
        return
      }
      
      // 处理特定设备的result主题
      if (topic.includes('/result')) {
        try {
          console.log(`📊 处理结果数据: ${JSON.stringify(data)}`)
          
          // 只接收时间字段，单位转换为秒
          if (data.time) {
            const timeValue = (parseFloat(data.time) / 1000).toFixed(3)
            console.log(`转换后的时间: ${timeValue}秒`)
            
            // 停止计时器
            clearInterval(timerInterval)
            timerInterval = null
            isTimerRunning.value = false
            
            // 更新当前数据
            currentTime.value = parseFloat(timeValue)
            
            // 更新当前未完成记录的时间，但不标记为完成
            if (hasActiveRace.value || (!isRecordCompleted.value && activeRecordId.value)) {
              updateRecordTime(parseFloat(timeValue))
              // 保存成绩记录
              saveRecord()
            } else {
              console.log('⚠️ 没有活动的比赛记录')
            }
          }
        } catch (error) {
          // 只记录错误，不显示提示
          console.error('❌ 处理结果数据出错:', error)
        }
        return
      }
    } catch (error) {
      // 只记录错误，不显示提示
      console.error('❌ 处理MQTT消息出错:', error)
    }
  })

  mqttClient.value.on('error', (err) => {
    console.error('❌ MQTT连接错误:', err)
    mqttStatus.value = 'disconnected'
    ElMessage.error('连接失败')
  })
  
  mqttClient.value.on('reconnect', () => {
    console.log('🔄 正在尝试重新连接MQTT服务器...')
  })
  
  mqttClient.value.on('close', () => {
    console.log('🔴 MQTT连接已关闭')
    mqttStatus.value = 'disconnected'
  })
}

// 成绩记录存储键前缀
const STORAGE_KEY_PREFIX = 'roller_records_'

// 保存成绩记录到本地存储
function saveRecordsToStorage() {
  try {
    const userId = '1' // 使用固定用户ID
    const deviceId = activeDeviceId.value
    const storageKey = `${STORAGE_KEY_PREFIX}${userId}_${deviceId}`
    
    localStorage.setItem(storageKey, JSON.stringify(records.value))
    console.log(`✅ 成功保存 ${records.value.length} 条成绩记录到本地存储`)
  } catch (error) {
    console.error('❌ 保存成绩记录失败:', error)
    ElMessage.error('保存成绩记录失败')
  }
}

// 从本地存储加载成绩记录
function loadRecordsFromStorage() {
  try {
    const userId = '1' // 使用固定用户ID
    const deviceId = activeDeviceId.value
    const storageKey = `${STORAGE_KEY_PREFIX}${userId}_${deviceId}`
    
    const storedRecords = localStorage.getItem(storageKey)
    if (storedRecords) {
      records.value = JSON.parse(storedRecords)
      console.log(`✅ 从本地存储加载了 ${records.value.length} 条成绩记录`)
    } else {
      console.log('本地存储中没有找到成绩记录')
      records.value = []
    }
  } catch (error) {
    console.error('❌ 加载成绩记录失败:', error)
    ElMessage.error('加载成绩记录失败')
    records.value = []
  }
}

// 保存成绩记录
function saveRecord() {
  console.log('保存成绩记录')
  // 如果没有有效的用时数据，则不保存记录
  if (currentTime.value <= 0) {
    console.warn('用时数据无效，不保存记录')
    return
  }
  
  // 如果当前没有进行中的比赛，不应该保存记录
  if (!hasActiveRace.value && isNewRace.value) {
    console.warn('没有进行中的比赛，不保存记录')
    return
  }
  
  // 格式化当前时间
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  const timestamp = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  
  // 创建记录
  const record = {
    id: Date.now(), // 使用时间戳作为唯一ID
    timestamp,
    time: currentTime.value,
    penaltyCount: penaltyCount.value,
    penaltyTime: penaltyTime.value,
    finalScore: finalScore.value,
    valid: isValidResult.value,
    groundTouch: groundTouch.value,
    completed: true // 标记为已完成
  }
  
  // 添加到记录列表
  records.value.unshift(record)
  
  // 保存到本地存储
  saveRecordsToStorage()
  
  console.log('成绩记录已保存:', record)
  ElMessage.success('成绩已保存')
  
  // 保存后清除进行中的比赛标记
  hasActiveRace.value = false
  // 如果再次编辑这条记录，则不是新比赛了
  isNewRace.value = false
  // 标记记录为已完成
  isRecordCompleted.value = true
}

// 删除记录
function deleteRecord(index) {
  ElMessageBox.confirm('确定要删除此记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    records.value.splice(index, 1)
    // 保存更新后的记录到本地存储
    saveRecordsToStorage()
    ElMessage.success('记录已删除')
  }).catch(() => {
    // 取消操作
  })
}

// 导出成绩记录到Excel
function exportRecords() {
  if (records.value.length === 0) {
    ElMessage.warning('没有可导出的成绩记录')
    return
  }

  // 准备导出数据
  const exportData = records.value.map(record => ({
    '时间': record.timestamp,
    '原始用时(秒)': record.time.toFixed(3),
    '漏桩数(个)': record.penaltyCount,
    '罚时(秒)': (record.penaltyCount * 0.2).toFixed(1),
    '最终成绩(秒)': record.valid ? record.finalScore.toFixed(3) : '无效',
    '状态': record.valid ? '有效' : '无效',
    '是否浮脚落地': record.groundTouch ? '是' : '否'
  }))

  // 创建工作簿
  const wb = XLSX.utils.book_new()
  const ws = XLSX.utils.json_to_sheet(exportData)

  // 设置列宽
  const colWidths = [
    { wch: 20 },  // 时间
    { wch: 12 },  // 原始用时
    { wch: 10 },  // 漏桩数
    { wch: 10 },  // 罚时
    { wch: 12 },  // 最终成绩
    { wch: 8 },   // 状态
    { wch: 12 }   // 是否浮脚落地
  ]
  ws['!cols'] = colWidths

  // 添加工作表到工作簿
  XLSX.utils.book_append_sheet(wb, ws, '速度过桩成绩记录')

  // 生成文件名
  const now = new Date()
  const fileName = `速度过桩成绩记录_${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}_${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}.xlsx`

  // 写入文件并下载
  XLSX.writeFile(wb, fileName)
  
  ElMessage.success('成绩记录已导出')
}

// 监听设备ID变化，加载对应的记录
watch(activeDeviceId, (newDeviceId) => {
  if (newDeviceId) {
    loadRecordsFromStorage()
  }
})

// 组件挂载时连接MQTT和初始化
onMounted(() => {
  connectMqtt()
  // 加载成绩记录
  loadRecordsFromStorage()
  
  // 检查是否有未完成的记录
  const incompleteRecord = records.value.find(record => !record.completed)
  if (incompleteRecord) {
    console.log('发现未完成的记录，正在清理...')
    // 找到未完成的记录并删除
    const index = records.value.indexOf(incompleteRecord)
    if (index !== -1) {
      records.value.splice(index, 1)
      saveRecordsToStorage()
    }
  }
  
  // 确保初始状态下没有进行中的比赛
  hasActiveRace.value = false
  isRecordCompleted.value = true
  activeRecordId.value = null
})

// 监听mqttClient和conesVisualizer的变化，确保正确设置
watch([() => mqttClient.value, () => conesVisualizer.value], ([newClient, newVisualizer]) => {
  if (newClient && newClient.connected && newVisualizer) {
    console.log('mqttClient和conesVisualizer都已就绪，设置MQTT客户端到可视化组件')
    newVisualizer.setMqttClient(newClient)
  }
}, { immediate: true })

// 处理设备连接
function handleDeviceConnection(data) {
  if (data.ready) {
    console.log(`📱 设备连接成功: ${data.ready}`)
    
    if (!connectedDevices.value.includes(data.ready)) {
      console.log(`📡 添加新设备到连接列表: ${data.ready}`)
      connectedDevices.value.push(data.ready)
      console.log(`当前已连接设备: ${JSON.stringify(connectedDevices.value)}`)
      
      // 为新连接的设备订阅主题
      console.log(`准备为设备 ${data.ready} 订阅专属主题...`)
      subscribeToDeviceTopics([data.ready])
    } else {
      console.log(`设备 ${data.ready} 已在连接列表中，无需重复添加`)
    }
    
    ElMessage.success(`设备 ${data.ready} 连接成功`)
  }
}

// 开始计时
function startTimer() {
  if (mqttClient.value && mqttStatus.value === 'connected') {
    // 使用当前选中的设备ID构建主题
    const publishTopic = `roller/timer/state`;
    const publishData = { race: 'on' };
    console.log(`📤 发送开始计时指令: 主题=${publishTopic}, 数据=`, publishData);
    
    // 标记比赛开始
    hasActiveRace.value = true
    isRecordCompleted.value = false
    
    mqttClient.value.publish(publishTopic, JSON.stringify(publishData))
    
    ElMessage.success('计时开始')
  } else {
    ElMessage.warning('MQTT未连接，无法发送指令')
  }
}

// 结束计时
function stopTimer() {
  if (mqttClient.value && mqttStatus.value === 'connected') {
    // 使用当前选中的设备ID构建主题
    const publishTopic = `roller/timer/state`;
    const publishData = { race: 'off' };
    console.log(`📤 发送结束计时指令: 主题=${publishTopic}, 数据=`, publishData);
    
    mqttClient.value.publish(publishTopic, JSON.stringify(publishData))
    
    // 标记比赛结束但不完成记录
    hasActiveRace.value = false
    
    ElMessage.success('计时结束')
  } else {
    ElMessage.warning('MQTT未连接，无法发送指令')
  }
}

// 重置系统
function resetSystem() {
  ElMessageBox.confirm('确定要重置系统吗？当前数据将会丢失。', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 无论MQTT连接状态如何，都执行本地重置
    console.log('用户确认重置系统')
    
    // 停止计时器
    if (timerInterval) {
      clearInterval(timerInterval)
      timerInterval = null
      isTimerRunning.value = false
    }
    
    // 重置计时数据
    currentTime.value = 0
    
    // 删除未完成的记录
    if (!isRecordCompleted.value && activeRecordId.value) {
      removeIncompleteRecord()
    }
    
    // 标记没有进行中的比赛
    hasActiveRace.value = false
    
    // 重置所有状态
    resetAllState()
    
    // 如果MQTT已连接，发送重置指令
    if (mqttClient.value && mqttStatus.value === 'connected') {
      // 使用当前选中的设备ID构建主题
      const publishTopic = `roller/timer/state`;
      const publishData = { reset: 'on' };
      console.log(`📤 发送重置指令: 主题=${publishTopic}, 数据=`, publishData);
      
      mqttClient.value.publish(publishTopic, JSON.stringify(publishData))
    } else {
      console.log('MQTT未连接，仅执行本地重置')
    }
    
    ElMessage.success('系统已重置')
  }).catch(() => {
    // 取消操作
    console.log('用户取消重置系统')
  })
}

// 重置所有状态
function resetAllState() {
  console.log('执行完全重置')
  
  // 停止计时器
  if (timerInterval) {
    clearInterval(timerInterval)
    timerInterval = null
  }
  
  // 重置所有状态
  isTimerRunning.value = false
  currentTime.value = 0
  startTime.value = 0
  penaltyCount.value = 0
  groundTouch.value = false
  
  // 重置比赛状态标志
  hasActiveRace.value = false
  isRecordCompleted.value = true
  activeRecordId.value = null
  
  // 重置桩桶状态
  if (conesVisualizer.value) {
    conesVisualizer.value.resetCones()
  }
  
  console.log('所有状态已重置')
}

// 更新最新记录
function updateLatestRecord() {
  if (records.value.length > 0 && !isRecordCompleted.value) {
    const latestRecord = records.value[0]
    
    // 更新记录中的数据
    latestRecord.time = currentTime.value
    latestRecord.penaltyCount = penaltyCount.value
    latestRecord.penaltyTime = penaltyTime.value
    latestRecord.finalScore = finalScore.value
    latestRecord.valid = isValidResult.value
    latestRecord.groundTouch = groundTouch.value
    
    // 记录更新后保存
    saveRecordsToStorage()
    console.log('记录已更新:', latestRecord)
  }
}

// 处理桩桶状态变化 - 更新踢漏桩数量
function handleConeStatusChange(coneData) {
  console.log(`桩桶状态变更: 漏桩数量=${coneData.missedCount}, 踢桩数量=${coneData.kickedCount}, 未检测数量=${coneData.noReceiveCount}`)
  
  // 更新漏桩踢桩总数量 (漏桩 + 踢桩)
  const totalPenaltyCount = coneData.missedCount + coneData.kickedCount
  
  // 更新当前数据中的漏桩踢桩数量
  penaltyCount.value = totalPenaltyCount
  
  console.log(`更新后的漏桩踢桩总数: ${penaltyCount.value}`)
  
  // 如果有未完成的记录，实时更新它
  if (!isRecordCompleted.value && records.value.length > 0) {
    updateLatestRecord()
  }
}

// 切换浮脚落地状态
function toggleGroundTouch() {
  groundTouch.value = !groundTouch.value
  ElMessage.success(`浮脚落地状态已修改为: ${groundTouch.value ? '是' : '否'}`)
}

// 打开漏桩踢桩修改对话框
function editPenalty() {
  editingPenaltyCount.value = penaltyCount.value
  penaltyDialogVisible.value = true
}

// 确认修改漏桩踢桩数量
function confirmPenaltyEdit() {
  penaltyCount.value = editingPenaltyCount.value
  penaltyDialogVisible.value = false
  ElMessage.success('漏桩踢桩数量已修改')
}

// 监听成绩数据变化，以便更新记录
watch([currentTime, penaltyCount, groundTouch], () => {
  // 如果有未完成的记录，实时更新它
  if (!isRecordCompleted.value && records.value.length > 0) {
    updateLatestRecord()
  }
}, { deep: true })

// 格式化时间，保留3位小数
function formatTime(time) {
  return time.toFixed(3)
}

// 组件销毁前清除计时器和MQTT连接
onBeforeUnmount(() => {
  if (timerInterval) {
    clearInterval(timerInterval)
  }
  
  // 清除未完成的记录
  if (!isRecordCompleted.value && activeRecordId.value) {
    removeIncompleteRecord()
  }
  
  if (mqttClient.value) {
    // 取消所有设备订阅
    connectedDevices.value.forEach(deviceId => {
      unsubscribeFromDeviceTopics(deviceId)
    })
    
    mqttClient.value.end()
  }
})

// 处理MQTT消息中的timer/control
function handleTimerControl(data) {
  console.log('处理计时控制指令:', data)
  
  if (data.race === 'on') {
    // 在创建新记录前，先完成上一条未完成的记录
    if (!isRecordCompleted.value && activeRecordId.value) {
      console.log('检测到未完成的上一条记录，标记为已完成')
      finalizeLastRecord()
    }
    
    // 收到开始指令时，标记有一个进行中的比赛
    hasActiveRace.value = true
    isRecordCompleted.value = false
    
    // 重置计时器并开始计时
    clearInterval(timerInterval)
    currentTime.value = 0
    startTime.value = Date.now()
    isTimerRunning.value = true
    
    timerInterval = setInterval(() => {
      currentTime.value = (Date.now() - startTime.value) / 1000
    }, 10)
    
    // 重置当前成绩数据，但保留桩桶在线状态
    resetCurrentData()
    
    // 创建新记录
    createNewRecord()
    
    console.log('比赛开始：计时器已启动，新记录已创建')
    ElMessage.success('比赛开始，计时中...')
  } else if (data.race === 'off') {
    // 收到结束指令时，停止计时器
    clearInterval(timerInterval)
    timerInterval = null
    isTimerRunning.value = false
    
    // 标记没有进行中的比赛，但记录仍然保持未完成状态
    hasActiveRace.value = false
    
    // 如果有时间数据，则更新记录
    if (currentTime.value > 0) {
      updateRecordTime(currentTime.value)
    }
    
    console.log('比赛结束：计时器已停止，等待桩桶状态完成更新')
    ElMessage.warning('比赛结束，等待桩桶状态更新')
  }
}

// 完成上一条记录 - 不再等待结果消息，在下一次比赛开始时完成
function finalizeLastRecord() {
  if (records.value.length > 0 && !isRecordCompleted.value) {
    const latestRecord = records.value[0]
    
    // 如果当前时间是0，则说明没有收到结果消息，使用计时器时间
    if (latestRecord.time === 0) {
      latestRecord.time = currentTime.value
    }
    
    // 确保罚时和最终成绩已更新
    latestRecord.penaltyCount = penaltyCount.value
    latestRecord.penaltyTime = penaltyTime.value
    latestRecord.finalScore = latestRecord.time + latestRecord.penaltyTime
    latestRecord.valid = isValidResult.value
    latestRecord.groundTouch = groundTouch.value
    
    // 标记为已完成
    latestRecord.completed = true
    
    // 保存到本地存储
    saveRecordsToStorage()
    
    // 更新状态
    isRecordCompleted.value = true
    activeRecordId.value = null
    
    console.log('上一条记录已完成:', latestRecord)
  }
}

// 重置当前成绩数据，但保留桩桶在线状态
function resetCurrentData() {
  // 清除踢漏桩数据
  penaltyCount.value = 0
  
  // 清除浮脚落地状态
  groundTouch.value = false
  
  // 重置桩桶状态（只清除状态，保留在线状态）
  if (conesVisualizer.value) {
    conesVisualizer.value.resetCones()
  }

}

// 取消订阅设备特定的主题
function unsubscribeFromDeviceTopics(deviceId) {
  if (!mqttClient.value || !mqttClient.value.connected) {
    return
  }
  
  const userId = '1'
  const controlTopic = `roller/timer/${deviceId}/${userId}/control`
  const resultTopic = `roller/timer/${deviceId}/${userId}/result`
  
  console.log(`📴 取消订阅设备 ${deviceId} 的主题:`)
  console.log(` - 控制主题: ${controlTopic}`)
  console.log(` - 结果主题: ${resultTopic}`)
  
  mqttClient.value.unsubscribe(controlTopic, (err) => {
    if (err) {
      console.error(`❌ 取消订阅控制主题失败: ${controlTopic}`, err)
    } else {
      console.log(`✅ 已成功取消订阅控制主题: ${controlTopic}`)
    }
  })
  
  mqttClient.value.unsubscribe(resultTopic, (err) => {
    if (err) {
      console.error(`❌ 取消订阅结果主题失败: ${resultTopic}`, err)
    } else {
      console.log(`✅ 已成功取消订阅结果主题: ${resultTopic}`)
    }
  })
  
  console.log(`设备 ${deviceId} 的主题已取消订阅`)
}

// 订阅设备特定的主题
function subscribeToDeviceTopics(specificDevices = null) {
  if (!mqttClient.value || !mqttClient.value.connected) {
    console.error('❌ 无法订阅设备主题: MQTT客户端未连接')
    return
  }
  
  // 强制使用固定用户ID "1"，不从localStorage获取
  const userId = '1'
  const devicesToSubscribe = specificDevices || connectedDevices.value
  
  console.log('===== 开始订阅设备主题 =====')
  console.log(`当前用户ID: ${userId}`)
  console.log(`需要订阅的设备列表: ${JSON.stringify(devicesToSubscribe)}`)
  
  if (!devicesToSubscribe || devicesToSubscribe.length === 0) {
    console.warn('⚠️ 没有可用设备需要订阅，请检查connectedDevices是否正确初始化')
    return
  }
  
  devicesToSubscribe.forEach(deviceId => {
    console.log(`处理设备: ${deviceId}`)
    
    if (!deviceId) {
      console.warn('⚠️ 设备ID为空，跳过订阅')
      return
    }
    
    // 订阅设备的控制主题
    const controlTopic = `roller/timer/${deviceId}/${userId}/control`
    // 订阅设备的结果主题
    const resultTopic = `roller/timer/${deviceId}/${userId}/result`
    
    console.log(`正在订阅设备 ${deviceId} 的主题:`)
    console.log(` - 控制主题: ${controlTopic}`)
    console.log(` - 结果主题: ${resultTopic}`)
    
    mqttClient.value.subscribe(controlTopic, (err) => {
      if (err) {
        console.error(`❌ 订阅控制主题失败: ${controlTopic}`, err)
      } else {
        console.log(`✅ 成功订阅控制主题: ${controlTopic}`)
      }
    })
    
    mqttClient.value.subscribe(resultTopic, (err) => {
      if (err) {
        console.error(`❌ 订阅结果主题失败: ${resultTopic}`, err)
      } else {
        console.log(`✅ 成功订阅结果主题: ${resultTopic}`)
      }
    })
  })
  
  console.log('===== 设备主题订阅完成 =====')
}

// 创建新记录
function createNewRecord() {
  console.log('创建新记录')
  // 格式化当前时间
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  const timestamp = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  
  // 新记录ID
  const recordId = Date.now()
  
  // 创建初始记录
  const record = {
    id: recordId,
    timestamp,
    time: 0, // 初始用时为0
    penaltyCount: penaltyCount.value,
    penaltyTime: penaltyTime.value,
    finalScore: 0, // 初始最终成绩为0
    valid: isValidResult.value,
    groundTouch: groundTouch.value,
    completed: false // 标记为未完成
  }
  
  // 添加到记录列表
  records.value.unshift(record)
  
  // 保存到本地存储
  saveRecordsToStorage()
  
  // 设置当前活动记录ID
  activeRecordId.value = recordId
  
  // 标记记录为未完成
  isRecordCompleted.value = false
  
  console.log('新记录已创建:', record)
}

// 更新记录的时间（在收到结果消息时）
function updateRecordTime(finalTime) {
  console.log('更新记录时间:', finalTime)
  if (!isRecordCompleted.value && activeRecordId.value) {
    const latestRecord = records.value.find(record => record.id === activeRecordId.value)
    if (latestRecord) {
      // 更新时间字段
      latestRecord.time = finalTime
      latestRecord.finalScore = finalTime + latestRecord.penaltyTime
      
      // 保存到本地存储
      saveRecordsToStorage()
      
      console.log('记录时间已更新:', latestRecord)
      ElMessage.success('成绩时间已更新')
    } else {
      console.warn('未找到进行中的记录')
    }
  } else {
    console.warn('没有未完成的记录可以更新')
  }
}

// 删除未完成的记录
function removeIncompleteRecord() {
  if (activeRecordId.value) {
    const index = records.value.findIndex(record => record.id === activeRecordId.value)
    if (index !== -1) {
      records.value.splice(index, 1)
      saveRecordsToStorage()
      console.log('未完成的记录已删除')
    }
    
    // 重置状态
    activeRecordId.value = null
    isRecordCompleted.value = true
  }
}

// 表格选择变化
function handleSelectionChange(selection) {
  selectedRecords.value = selection
}

// 批量删除记录
function batchDeleteRecords() {
  if (selectedRecords.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRecords.value.length} 条记录吗？`, 
    '提示', 
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 获取所有要删除的记录ID
    const idsToDelete = selectedRecords.value.map(record => record.id)
    
    // 从数组中过滤掉要删除的记录
    records.value = records.value.filter(record => !idsToDelete.includes(record.id))
    
    // 重置选中数组
    selectedRecords.value = []
    
    // 保存到本地存储
    saveRecordsToStorage()
    
    ElMessage.success(`成功删除 ${idsToDelete.length} 条记录`)
  }).catch(() => {
    // 取消操作
  })
}

// 组件激活时执行（从其他页面返回时）
onActivated(() => {
  console.log('个人赛页面被激活')
  
  // 检查是否有未完成的记录或有活动比赛
  if (!isRecordCompleted.value || hasActiveRace.value) {
    // 有未完成的记录或比赛进行中，恢复MQTT连接
    if (!mqttClient.value || !mqttClient.value.connected) {
      console.log('恢复MQTT连接')
      connectMqtt()
    }
    
    // 如果有计时器运行，但时间显示不正确，重新开始计时器
    if (isTimerRunning.value && timerInterval === null) {
      console.log('恢复计时器')
      startTime.value = Date.now() - (currentTime.value * 1000)
      timerInterval = setInterval(() => {
        currentTime.value = (Date.now() - startTime.value) / 1000
      }, 10)
    }
    
    console.log('保持比赛数据状态')
  } else {
    console.log('没有进行中的比赛，无需保持状态')
    // 无需保持状态，可以执行刷新操作
  }
})

// 组件停用时执行（切换到其他页面时）
onDeactivated(() => {
  console.log('个人赛页面被停用')
  
  // 如果没有未完成的记录和活动比赛，可以停止计时器节省资源
  if (isRecordCompleted.value && !hasActiveRace.value) {
    // 停止计时器
    if (timerInterval) {
      console.log('停止计时器')
      clearInterval(timerInterval)
      timerInterval = null
    }
    
    // 不断开MQTT连接，只在组件销毁时断开
    console.log('保持MQTT连接')
  } else {
    // 有未完成的记录或比赛进行中，保持所有状态
    console.log('保持所有状态和连接')
  }
})
</script>

<style scoped>
/* 控制按钮组 */
.control-panel {
  position: relative;
  right: 130px;
  display: flex;
  gap: 15px;
  z-index: 5;
}

.control-btn {
  border: none !important;
  position: relative;
  overflow: hidden;
  border-radius: 12px !important;
  font-weight: 600 !important;
  min-width: 70px !important;
  padding: 10px 16px !important;
}

.control-btn.success {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%) !important;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

.control-btn.success:hover {
  box-shadow: 0 6px 16px rgba(103, 194, 58, 0.4);
  transform: translateY(-2px);
}

.control-btn.danger {
  background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%) !important;
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
}

.control-btn.danger:hover {
  box-shadow: 0 6px 16px rgba(245, 108, 108, 0.4);
  transform: translateY(-2px);
}

.control-btn.primary {
  background: linear-gradient(135deg, #409EFF 0%, #36acfe 100%) !important;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.control-btn.primary:hover {
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
  transform: translateY(-2px);
}

.control-btn::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0));
  z-index: 0;
}

.control-btn :deep(i),
.control-btn :deep(span) {
  position: relative;
  z-index: 1;
}

/* 数据卡片区域 */
.data-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 0;
}

.data-card {
  background: white;
  border-radius: 16px;
  padding: 20px;
  height: 150px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  position: relative;
  overflow: hidden;
}

.data-card::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.5) 0%, rgba(255, 255, 255, 0) 60%);
  pointer-events: none;
}

.time-card {
  border-left: 4px solid #409EFF;
  background: linear-gradient(135deg, #ffffff 0%, #f0f7ff 100%);
}

.pile-card {
  border-left: 4px solid #e6a23c;
  background: linear-gradient(135deg, #ffffff 0%, #fff9f0 100%);
}

.land-card {
  border-left: 4px solid #f56c6c;
  background: linear-gradient(135deg, #ffffff 0%, #fff0f0 100%);
}

.card-icon {
  font-size: 24px;
  margin-bottom: 10px;
  color: #409EFF;
  background: rgba(64, 158, 255, 0.1);
  width: 42px;
  height: 42px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.pile-card .card-icon {
  color: #e6a23c;
  background: rgba(230, 162, 60, 0.1);
}

.land-card .card-icon {
  color: #f56c6c;
  background: rgba(245, 108, 108, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.edit-button {
  font-size: 14px;
  color: #409EFF;
}

.card-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
  font-weight: 500;
}

.card-value {
  font-size: 36px;
  font-weight: 700;
  color: #303133;
  line-height: 1.2;
}

.unit {
  font-size: 14px;
  color: #909399;
  font-weight: 400;
  margin-left: 4px;
}

/* 最终成绩 */
.final-result-text {
  margin-bottom: 0;
  padding: 25px 30px;
  background-color: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.05);
  border-left: 4px solid #409EFF;
  background: linear-gradient(135deg, #ffffff 0%, #f0f7ff 100%);
  text-align: center;
}

.result-section h3 {
  font-size: 26px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  display: inline-block;
  position: relative;
  padding-left: 15px;
  text-align: left;
}

.result-section h3::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 5px;
  height: 25px;
  background: linear-gradient(135deg, #409EFF 0%, #36acfe 100%);
  border-radius: 3px;
}

.status-badge {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  margin-left: 10px;
  color: white;
}

.status-badge.valid {
  background-color: #67c23a;
}

.status-badge.invalid {
  background-color: #f56c6c;
}

.final-score-value {
  font-size: 42px;
  font-weight: 700;
  color: #409EFF;
  margin: 15px 0;
  text-align: center;
  font-family: 'Courier New', monospace;
}

.score-note {
  font-size: 14px;
  color: #909399;
  text-align: center;
}

/* 成绩记录 */
.records-section {
  padding: 25px 30px;
  background-color: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.05);
  margin-bottom: 0;
  border-left: 4px solid #409EFF;
  background: linear-gradient(135deg, #ffffff 0%, #f0f7ff 100%);
}

.records-title {
  font-size: 26px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  display: inline-block;
  position: relative;
  padding-left: 15px;
}

.records-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 5px;
  height: 25px;
  background: linear-gradient(135deg, #409EFF 0%, #36acfe 100%);
  border-radius: 3px;
}

.records-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.simple-button {
  padding: 8px 16px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.3s;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.simple-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.3);
}

.simple-button.danger {
  background-color: #f56c6c;
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.2);
}

.simple-button.danger:hover {
  box-shadow: 0 6px 16px rgba(245, 108, 108, 0.3);
}

.simple-button:disabled {
  background-color: #c0c4cc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.records-table {
  margin-top: 15px;
  border-radius: 8px;
  overflow: hidden;
}

.records-table :deep(.el-table__header) {
  background-color: #f5f7fa;
}

.records-table :deep(th) {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: 500;
  padding: 12px 8px;
  font-size: 14px;
}

.records-table :deep(td) {
  padding: 12px 8px;
  font-size: 13px;
}

.time-value {
  font-family: monospace;
  color: #606266;
}

.penalty-value {
  color: #e6a23c;
  font-family: monospace;
}

.final-score {
  color: #409EFF;
  font-weight: 600;
  font-family: monospace;
}

.final-score.invalid {
  color: #f56c6c;
}

.status {
  color: #67c23a;
}

.status.invalid {
  color: #f56c6c;
}

.delete-btn {
  padding: 2px 8px;
  color: #f56c6c !important;
  font-size: 13px;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .data-cards {
    grid-template-columns: repeat(3, 1fr);
  }
  
  .data-card {
    height: 140px;
    padding: 15px;
  }
  
  .card-value {
    font-size: 30px;
  }
}

@media (max-width: 768px) {
  .data-cards {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .data-card {
    height: auto;
    padding: 15px;
  }
  
  .control-panel {
    flex-wrap: wrap;
  }
  
  .final-score-value {
    font-size: 36px;
  }
  
  .records-table {
    font-size: 12px;
  }
  
  .records-section,
  .final-result-text {
    padding: 20px;
  }
}
</style> 